/* eslint-disable import/no-extraneous-dependencies */
/* eslint-disable no-continue */
/* eslint-disable no-console */
/* eslint-disable no-restricted-syntax */
/* eslint-disable no-plusplus */
/**
 * 这个脚本的目的是从公版的仓库里同步代码，仅同步公版里新增的且不存在当前仓库的文件。
 * 使用方法：
 * node sync-new-files.js --hlydir=../huilianyi-refactoring
 *
 * --hlydir参数：公版仓库相对于当前目录的本地路径。
 */

const fs = require("fs").promises;
const glob = require("glob");
const argv = require("yargs").argv;
const path = require("path");

// 0不存在 1文件 2目录
async function getFileType(filename) {
  try {
    const filestat = await fs.stat(filename);
    if (filestat.isDirectory()) return 2;
    return 1;
  } catch (e) {
    return 0;
  }
}

async function main() {
  if (!argv.hlydir) {
    console.log("请使用参数hlydir");
    return;
  }
  const hlydir = path.resolve(process.cwd(), argv.hlydir);
  const hlydirType = await getFileType(hlydir);
  if (hlydirType === 0) {
    console.log("hlydir不存在");
    return;
  }
  if (hlydirType === 1) {
    console.log("hlydir不是一个目录");
    return;
  }
  console.log(`hlydir: ${hlydir}`);
  const hlysrcdir = path.resolve(hlydir, "./src");
  const srcdir = path.resolve(__dirname, "./src");

  const files = glob.sync(path.resolve(hlysrcdir, "./**/*"));
  let fileCount = 0;
  let folderCount = 0;
  for (const file of files) {
    const fileType = await getFileType(file);
    const relativeFilename = path.relative(hlysrcdir, file);
    const currentFilename = path.resolve(srcdir, relativeFilename);
    const fileType2 = await getFileType(currentFilename);
    if (fileType2 > 0) continue;
    if (fileType === 2) {
      await fs.mkdir(currentFilename);
      console.log(`新增目录：${relativeFilename}`);
      folderCount++;
    } else {
      await fs.copyFile(file, currentFilename);
      console.log(`复制文件：${relativeFilename}`);
      fileCount++;
    }
  }

  console.log(`共迁移${fileCount}个文件，${folderCount}个目录`);
}

main();
